package com.zbl.zblproject.contract.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zbl.zblproject.contract.entity.Contract;
import com.zbl.zblproject.contract.entity.Rebates;
import com.zbl.zblproject.contract.mapper.ContractMapper;
import com.zbl.zblproject.contract.mapper.RebatesMapper;
import com.zbl.zblproject.contract.service.ContractService;
import com.zbl.zblproject.core.utils.StringUtil;
import com.zbl.zblproject.core.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2019/3/14
 */
@Service
public class ContractServiceImpl implements ContractService {

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private RebatesMapper rebatesMapper;


    @Override
    public IPage<Contract> selectPage(IPage<Contract> page, String start, String end, String search) {
        QueryWrapper<Contract> wrapper = new QueryWrapper<>();

        if (!StringUtil.isNullOrEmpty(search)) {
            wrapper.like("suppliers_name", search);
        }
        if (!StringUtil.isNullOrEmpty(start)) {
            wrapper.ge("start_time", TimeUtil.parseTime(start));
        }
        if (!StringUtil.isNullOrEmpty(end)) {
            wrapper.le("end_time", TimeUtil.parseTime(end));
        }

        page = contractMapper.selectPage(page, wrapper);
        page.getRecords().forEach(x->{
            x.setRebates(rebatesMapper.selectRebatesByContractId(x.getContractId()));
        });
        return page;
    }

    @Override
    @Transactional
    public boolean addContract(Contract contract, List<Rebates> rebates) {
        boolean result = false;
        result = contractMapper.insert(contract) == 1;
        if (result) {
            for (Rebates rebate : rebates) {
                rebate.setContractId(contract.getContractId());
                rebatesMapper.insert(rebate);
            }
        }
        return result;
    }

    @Override
    @Transactional
    public boolean updateContract(Contract contract, List<Rebates> rebates) {
        boolean result = false;
        result = 1 == contractMapper.updateById(contract);
        rebatesMapper.deleteByContractId(contract.getContractId());
        if (result) {
            for (Rebates rebate : rebates) {
                rebate.setContractId(contract.getContractId());
                rebatesMapper.insert(rebate);
            }
        }
        return result;
    }

    @Override
    public boolean deleteContract(List<Integer> list) {
        return contractMapper.deleteBatchIds(list) > 0;
    }

    public boolean deleteContract(Integer id) {
        return contractMapper.deleteById(id) == 1;
    }
}
